//
//  SubDetailViewController.m
//  ZAKER
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SubDetailViewController.h"



@interface SubDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

{
    
    NSInteger _itemNum; // 记录tableView所在的item号
    
}

@property (nonatomic, retain) NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableArray *brray;
@property (nonatomic, retain) NSMutableArray *urlArr; //  存放webView网址
@property (nonatomic, retain) NSString *refreshStr; // 刷新界面时候, 他网址传到自定义的collectionViewCell中.

@property (nonatomic, retain) NSArray *arr;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) MBProgressHUD *mb;

@property (nonatomic, retain) UIView *leftView;

// 小圈圈
@property (nonatomic, retain) UIActivityIndicatorView *acticity;



@end

@implementation SubDetailViewController
-(void)dealloc
{
    [_acticity release];
    [_arr release];
    [_tableView release];
    [_labelStr release];
    [_brray release];
    [_urlArr release];
    [_myArray release];
    [_refreshStr release];
    [_mb release];
    
    [super dealloc];
    
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        
        [_leftView release];
        
        self.page = 1;
        self.myArray = [NSMutableArray array];
        self.brray = [NSMutableArray array];
        self.urlArr = [NSMutableArray array];
        self.arr = [NSArray arrayWithObjects:@"203",@"117", @"202", @"183", @"293", @"142",@"138", @"123", @"313",nil];
    }
    
    return self;
    
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self creatTableview];
    
    self.navigationController.navigationBar.barTintColor  = RGBACOLOR(135, 206, 255, 1);
    
    self.myTag = 1;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(150 * myWidth, 10 * myHeight, 75 * myWidth, 40 * myHeight)];
    label.text = self.labelStr;
    self.navigationItem.titleView = label;
    [label release];
    
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _mb = [[MBProgressHUD alloc] initWithView:window];
    [self.view addSubview:_mb];
    _mb.labelText = @"正在加载";
    [_mb show:YES];
    [self myConnection];
    
     // 15秒后,如果数据还没请求出来, 就停止
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)15 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if (_mb != nil) {
            [_mb removeFromSuperview];
            
            UIAlertController *a = [UIAlertController alertControllerWithTitle:@"提示" message:@"数据加载失败" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [a addAction:sure];
            // 模态推出
            [self presentViewController:a animated:YES completion:^{
                
            }];
        }
    });
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    UILabel *labels = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 37.5 * myWidth, 12 , 75 * myWidth, 40 * myHeight)];
    labels.text = @"订阅";
    labels.textAlignment = 1;
    self.navigationItem.titleView = labels;
    [labels release];
   
    
    
    [self instrustButton];
    [self changeNavigation];
    [self moreButton];
    
    
}


- (void)creatTableview
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 * myHeight) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView release];
    [self refresh];
}


- (void)changeNavigation
{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"111.png"] style:UIBarButtonItemStyleDone target:self action:@selector(showMoreButton)];

    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
}
- (void)moreButton
{
    self.leftView = [[UIView alloc]initWithFrame:CGRectMake(-100 * myWidth, 0, 100 * myWidth, self.view.frame.size.height - 49 * myHeight)];
    [self.view addSubview:_leftView];
    [_leftView release];
    _leftView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.5];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.leftView addGestureRecognizer:tap];
    [tap release];
    
    
    NSArray *nameArray = [NSArray arrayWithObjects:@"娱乐八卦", @"商业圈",@"体育频道", @"时尚先生", @"军事",@"财经新闻",  @"名车志",@"科技",  @"旅游频道", nil];
    for (int i = 0; i < 9; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"mumu.png"] forState:UIControlStateNormal];
        [button setTitle:[nameArray objectAtIndex:i] forState:UIControlStateNormal];
        button.tag = i + 1;
        [_leftView addSubview:button];
        [button addTarget:self action:@selector(priceAction:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleShadowColor:[UIColor brownColor] forState:UIControlStateNormal];
        button.showsTouchWhenHighlighted = YES;
        button.frame = CGRectMake(0, button.tag * button.frame.size.height, 100 * myWidth, 50 * myHeight);
    }
}

#pragma mark - 点击灰色背景收起左侧菜单
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    UIView *view = tap.view;
    [UIView animateWithDuration:0.4 animations:^{
        view.frame = CGRectMake(-100 * myWidth, 0, 100 * myWidth, self.view.frame.size.height - 49 * myHeight);
        [self.acticity stopAnimating];
    }];
}

- (void)showMoreButton
{
    NSArray *aa = self.leftView.subviews;
    for (UIButton *but in aa) {
        if ([but isKindOfClass:[UIButton class]]) {
            but.frame = CGRectMake(0, but.tag * but.frame.size.height, 100 * myWidth, 50 * myHeight);
        }
    }
    [UIView animateWithDuration:0.5 animations:^{
        _leftView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49 * myHeight);
    }];
    
}


-(void)priceAction:(id)sender
{
    #pragma mark - 小圆圈
        self.acticity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
        self.acticity.center = self.leftView.center;
        self.acticity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        [self.leftView addSubview:self.acticity];
        [self.acticity startAnimating];
        [_acticity release];
    
    NSArray *aa = self.leftView.subviews;
    for (UIButton *but in aa) {
        
        if ([but isKindOfClass:[UIButton class]]) {
            CGRect rect = but.frame;
            but.frame = CGRectMake(0, rect.origin.y, 100 * myWidth, 50 * myHeight);
            
        }
    }
    
    UIButton *button = (UIButton *)sender;
    CGRect rectbutt = button.frame;
    button.frame = CGRectMake(0, rectbutt.origin.y, 150 * myWidth, 50 * myHeight);
    self.myTag = button.tag;
    [self myConnection];
    
}


#pragma mark - 创建collectionView以及实现协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.myArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"abc"];
    if (!cell) {
        cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"abc"];
    }
    CellModel *model = [self.myArray objectAtIndex:indexPath.row];
    
    [cell.myImage sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"zhan.jpg"]];
    cell.titleLabel.text = model.title;
    
    // 判断如果数组为空
    if ([model.taginfo isEqual:@""]) {
    } else {
        
        NSArray *array = model.taginfo;
        NSDictionary *dic = array[0];
        NSString *str = dic[@"name"];
        cell.nameLabel.text = str;
        
    }
    
    NSInteger time = (  [model.update_time integerValue] - [model.publishtime integerValue]) / 3600;
    if (time < 0) {
        
        time = -time;
        cell.timeLabel.text = [NSString stringWithFormat:@"%ld小时前",time ];
        
    } else if (time == 0){
        
        cell.timeLabel.text = @"刚刚更新" ;
        
    } else {
        
        cell.timeLabel.text = [NSString stringWithFormat:@"%ld小时前", time];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 250 * myHeight;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 获取到点击的是哪个item的那个row 然后从数组中取出model
    NSInteger numberNum = _itemNum * 3 + indexPath.row;
    
    
    if ([_myArray count] > numberNum) {
        
        CellModel *model = _myArray[numberNum];
        WedViewController *web  = [[WedViewController alloc] init];
        web.model = model;
        [self.navigationController pushViewController:web animated:YES];
        [web release];
        
    }
}


#pragma mark - 滑动隐藏显示左边栏
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}


#pragma mark - 提示左右滑动的透明button
-(void)instrustButton
{
    // 第一次进入提示, 以后不需要提示
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@"instruct"] == nil) {
        [user setValue:@"i" forKey:@"instruct"];
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        button.alpha = 0.85;
        button.backgroundColor = [UIColor grayColor];
        
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        [window addSubview:button];
        [button setImage:[UIImage imageNamed:@"button2.jpg"] forState:UIControlStateNormal];
        
        // 三秒后消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [button removeFromSuperview];
        });
        
        [button addTarget:self action:@selector(instrusAction:) forControlEvents:UIControlEventTouchUpInside];
        [button release];
        
    }
}


#pragma mark - 点击之后, 从window上移除
-(void)instrusAction:(UIButton *)button
{
    [button removeFromSuperview];
}


#pragma  mark - 数据解析
-(void)myConnection
{
    NSInteger tag = self.myTag;
    
    // 拼接id, 进入各自对应的webView
    
    self.refreshStr = [NSString stringWithFormat:@"http://api.m.jiemian.com/article/cate/%@.json?page=1&version=2.1.1&page=1", [_arr objectAtIndex:tag -1]];
    [MyAFNetworking GetWithURL:_refreshStr dic:nil data:^(id responsder) {
        
        NSDictionary *dictionary = [responsder objectForKey:@"result"];
        NSArray *array = [dictionary objectForKey:@"rst"];
        [self.myArray removeAllObjects];
        
        for (int i = 0; i < [array count]; i++) {
            
            CellModel *model = [[CellModel alloc]init];
            [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
            [self.myArray addObject:model];
            [model release];
            
        }
        [UIView animateWithDuration:0.4 animations:^{
            NSArray *aa = self.leftView.subviews;
            for (UIButton *but in aa) {
                if ([but isKindOfClass:[UIButton class]]) {
                    CGRect rect = but.frame;
                    but.frame = CGRectMake(0, rect.origin.y, 100 * myWidth, 50 * myHeight);
                    
                }
            }

            self.leftView.frame = CGRectMake(-100 * myWidth, 0, 100 * myWidth, self.view.frame.size.height - 49 * myHeight);
        }];
        [self.tableView reloadData];
        
        [self.acticity stopAnimating];
        [_mb hide:YES];
        _mb = nil;
        
    }];
    
}
- (void)refresh
{

        // 添加上拉刷新控件
        [self.tableView addFooterWithCallback:^{
             NSInteger tag = self.myTag;
            self.page = self.page + 1;
            self.refreshStr = [NSString stringWithFormat:@"http://api.m.jiemian.com/article/cate/%@.json?page=%ld&version=2.1.1&page=%ld", [_arr objectAtIndex:tag -1], self.page, self.page];

            [MyAFNetworking GetWithURL:_refreshStr dic:nil data:^(id responsder) {
                NSDictionary *dictionary = [responsder objectForKey:@"result"];
                NSArray *array = [dictionary objectForKey:@"rst"];
                
                for (int i = 0; i < [array count]; i++) {
                    
                    CellModel *model = [[CellModel alloc]init];
                    [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
                    [self.myArray addObject:model];
                    [model release];
                    
                    
            }
                [self.tableView reloadData];
                
                [_mb hide:YES];
                _mb = nil;
                
                [self.tableView headerEndRefreshing];
                [self.tableView footerEndRefreshing];
            }];


        }];
    
        // 添加下拉加载控件
        [self.tableView addHeaderWithCallback:^{
            
            
            self.page = 1;
                NSInteger tag = self.myTag;
                self.refreshStr = [NSString stringWithFormat:@"http://api.m.jiemian.com/article/cate/%@.json?page=1&version=2.1.1&page=1", [_arr objectAtIndex:tag -1]];
                [MyAFNetworking GetWithURL:_refreshStr dic:nil data:^(id responsder) {
                    
                    NSDictionary *dictionary = [responsder objectForKey:@"result"];
                    NSArray *array = [dictionary objectForKey:@"rst"];
                    
                    [self.myArray removeAllObjects];
                    for (int i = 0; i < [array count]; i++) {
                        CellModel *model = [[CellModel alloc]init];
                        [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
                        [self.myArray addObject:model];
                        [model release];
                    }
                    [self.tableView reloadData];
                    
                    [_mb hide:YES];
                    _mb = nil;
                    
                    [self.tableView headerEndRefreshing];
                    [self.tableView footerEndRefreshing];
                    }];
            
        }];

    
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.leftView.frame = CGRectMake(-100 * myWidth, 0, 100 * myWidth, self.view.frame.size.height - 49 * myHeight);
}

@end
